#encoding:utf-8
'''
FileName:proxy.py
Creator:王烨
Date:2010.5.24
'''
from twisted.internet.defer import Deferred
from controller import Controller

class Proxy(object):
    '''RPC本地代理'''
    class __Proxy(object):
        def __init__(self, stub):
            self.__stub = stub
            
        def __getattr__(self, key):
            def CallAsync(method, request):
                d = Deferred()
                controller = Controller()
                method(controller, request, d.callback)
                return d
            
            def CallSync(method, request):
                controller = Controller()
                return method(controller, request)
            
            if key.endswith('Async'):
                key = key[:-5]
                call = CallAsync
            else:
                call = CallSync
            return lambda request : call(getattr(self.__stub, key), request)
        
    def __init__(self, *stubs):
        self.__stubs = {}
        for item in stubs:
            self.__stubs[item.GetDescriptor().name] = self.__Proxy(item)
            
    def __getattr__(self, key):
        return self.__stubs[key]